package cn.kgc.shiro.shiro;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;

/**
 * @author 课工场
 * @date 2023/11/21
 * @description shiro +springboot 整合配置
 */
@Configuration
public class ShiroConfig {

    //  shiroFilter
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);
        //  设置后台资源的过滤规则
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        //  放行登录请求   anon   AnonymousFilter
        map.put("/users/login","anon");
        // authc   FormAuthenticationFilter  表示所有的请求都要经过表单认证
        map.put("/**","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        // 设置用户没有认证时 跳转的路径
        shiroFilterFactoryBean.setLoginUrl("/users/unAuthenticated");

        return shiroFilterFactoryBean;
    }


    // 安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(Realm realm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(realm);

        return defaultWebSecurityManager;
    }

    // 自定义的realm
    @Bean
    public Realm realm() {
        CustomerRealm customerRealm = new CustomerRealm();
        // 创建凭证匹配器对象
        HashedCredentialsMatcher md5 = new HashedCredentialsMatcher("MD5");
        // 设置凭证匹配器 hash的次数
        md5.setHashIterations(10);
        customerRealm.setCredentialsMatcher(md5);
        return customerRealm;
    }

}
